package com.pengcheng.hnweb.controller;

import com.pengcheng.hnweb.job.TestJob;
import com.pengcheng.hnweb.service.DbService;
import com.pengcheng.hnweb.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.util.*;

@Component
@Slf4j
public class RmController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DbService dbService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private Common common;
    @Autowired
    private RabbitUtil rabbitUtil;
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private ControllerUtil controllerUtil;
    @Autowired
    private TestJob testJob;

    @Value("${spring.redis.expire}")
    private int expire;

    private boolean check=true;
    @RabbitListener(queues="hnww.msg",containerFactory="rabbitListenerContainerFactory",concurrency = "70")
    public void get_msg(Map<String,Object> map)
    {
        String channel_id="get_msg";
        String type="-2";
        try {
            type=map.get("type").toString();
            if(type.equals("-1"))
            {
                //充值hnww_device.state;//交给hngateway来处理
//                String sql1="update hnww_device set state=0 where deleted=0";
//                jdbcTemplate.update(sql1);
                fileUtil.add_msg("reboot","收到重启消息");
                return;
            }
            String msg=map.get("msg").toString();
            channel_id=map.get("channel_id").toString();
//            log.info("hnww.msg:"+map.toString());
            if(!msg.equals("48592D494F3434343043"))
            {
                fileUtil.add_msg(channel_id,msg);
                fileUtil.add_msg("get_msg",channel_id+":"+msg);
            }
            String sql="";
            if(msg.startsWith("0103"))
            {
                //主动上报
                Map<String,Object> data=common.decode(msg);
                log.info("data:"+data);
                if(data!=null)
                {
//                    log.info(data.toString());
                    sql="select * from hnww_device where deleted=0 and channel_id=?";
                    List<Map<String,Object>> rs=jdbcTemplate.queryForList(sql,channel_id);
                    if(rs!=null&&rs.size()>0)
                    {
                        String device_id=rs.get(0).get("id").toString();
                        //软开关
                        String dsend=rs.get(0).get("dsend").toString();
                        String field_60=rs.get(0).get("field_60").toString();
                        log.info(rs.get(0).toString());
                        //如果是重复的话则不保存
                        sql="select * from hnww_dlog"+device_id+" where device_id=? and ddate=?";
                        Object[] ps2={device_id,data.get("ddate").toString()};
                        List<Map<String,Object>> rs2=jdbcTemplate.queryForList(sql,ps2);
                        if(rs2==null||rs2.size()==0)
                        {
                            int dlog_id=controllerUtil.get_id_fordlog();
                            if(dlog_id<=0)
                            {
                                fileUtil.add_msg("get_msg",channel_id+":获取dlog_id失败");
                                return;
                            }
                            data.put("id",dlog_id);
                            data.put("deleted",0);
                            data.put("fdate",common.format_date(new Date()));
                            data.put("device_id",Integer.parseInt(device_id));
                            List<Map<String,Object>> columns_dlog=dbService.columns("dlog");
                            dbService.save(columns_dlog,"dlog"+device_id,data);
                            sql="INSERT INTO hnww_dloglast SELECT * FROM hnww_dlog" + device_id + " WHERE id="+dlog_id;
                            jdbcTemplate.update(sql);
                            //如果开启软件双发就添加dsendtask
                            if(dsend.equals("1")&&!common.is_empty(field_60))
                            {
                                Map<String,Object> row_dsendtask=new HashMap<>();
                                row_dsendtask.put("device_id",device_id);
                                row_dsendtask.put("dlog_id",dlog_id);
                                row_dsendtask.put("msg","");
                                row_dsendtask.put("ip","");
                                row_dsendtask.put("port",0);
                                row_dsendtask.put("ftime",0);
                                row_dsendtask.put("deleted",0);
                                List<Map<String,Object>> columns_dsendtask=dbService.columns("dsendtask");
                                dbService.save(columns_dsendtask,"dsendtask",row_dsendtask);
                            }
                        }
                        //回复消息
                        byte[] respon=common.get_response(msg);
                        Map<String,Object> msg_rabbit=new HashMap<>();
                        msg_rabbit.put("type",4);
                        msg_rabbit.put("channel_id",channel_id);
                        msg_rabbit.put("msg",common.byte2hex(respon));
                        rabbitTemplate.convertAndSend("hnww.respon",msg_rabbit);
                        //是否有卡号，如果有则更新
                        String iccd=redisUtil.get(channel_id+":iccd");
                        if(!common.is_empty(iccd))
                        {
                            sql="update hnww_device set iccd=? where id=?";
                            jdbcTemplate.update(sql,new Object[]{iccd,device_id});
                        }
                        else {
                            rabbitUtil.open_iccd(channel_id);
                            rabbitUtil.restart(channel_id);
                        }
                    }
                }
                else {
                    log.info("主动上报数据失败:"+msg);
                }
            }
            else if(msg.startsWith("68")&&msg.endsWith("16"))
            {
                Map<String,Object> data=common.decode_old(msg);
                if(data!=null)
                {
                    String sn=data.get("sn").toString();
                    sql="select * from hnww_device where deleted=0 and sn=?";
                    List<Map<String,Object>> rs=jdbcTemplate.queryForList(sql,sn);
                    sql="select * from hnww_device where deleted=0 and channel_id=?";
                    List<Map<String,Object>> rs1=jdbcTemplate.queryForList(sql,channel_id);
                    String device_id="";
                    String dsend="";
                    String field_60="";
                    if(rs1.size()==0)
                    {
                        //国控设备
                        if(rs==null||rs.size()==0)
                        {
                            sql="insert into hnww_device (`name`,channel_id,sn,state,deleted) values (?,?,?,?,?);";
                            Object[] ps3={"",channel_id,sn,1,0};
                            int new_device_id=jdbcTemplate.update(sql,ps3);
                            String table_name = "hnww_dlog" + new_device_id;
                            sql = "SELECT table_name FROM information_schema.tables where table_name=?";
                            List<Map<String, Object>> list_info = jdbcTemplate.queryForList(sql, new Object[]{table_name});
                            if (list_info.size() == 0)
                            {
                                sql="CREATE TABLE \"hnww\".\""+table_name+"\" (LIKE \"hnww\".\"hnww_dlog\" INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING DEFAULTS INCLUDING COMMENTS);";
                                jdbcTemplate.update(sql);
                            }
                            sql="update hnww_device set table_name=? where id=?";
                            jdbcTemplate.update(sql,new Object[]{table_name,new_device_id});
                            sql="select * from hnww_device where deleted=0 and sn=?";
                            rs=jdbcTemplate.queryForList(sql,channel_id);
                        }
                        if(rs!=null&&rs.size()>0)
                        {
                            sql="update hnww_device set channel_id=?,state=1 where sn=?";
                            Object[] ps4={channel_id,sn};
                            jdbcTemplate.update(sql,ps4);
                            device_id=rs.get(0).get("id").toString();
                            //软开关
                            dsend=rs.get(0).get("dsend").toString();
                            field_60=rs.get(0).get("field_60").toString();
                        }
                    }
                    else
                    {
                        device_id=rs1.get(0).get("id")+"";
                        //软开关
                        dsend=rs1.get(0).get("dsend").toString();
                        field_60=rs1.get(0).get("field_60").toString();
                    }
                    //如果是重复的话则不保存
//                    sql="select * from hnww_dlog"+device_id+" where device_id=? and ddate=?";
//                    Object[] ps2={device_id,data.get("ddate").toString()};
//                    List<Map<String,Object>> rs2=jdbcTemplate.queryForList(sql,ps2);
//                    if(rs2.size()>0)
//                    {
//                        fileUtil.add_msg("get_msg",channel_id+":数据重复");
//                        return;
//                    }
                    //插入dlog
                    int dlog_id=controllerUtil.get_id_fordlog();
                    if(dlog_id<=0)
                    {
                        fileUtil.add_msg("get_msg",channel_id+":获取dlog_id失败");
                        return;
                    }
                    data.put("id",dlog_id);
                    data.put("deleted",0);
                    String now=common.format_date(new Date());
                    String now_date=now.substring(0,10);
                    int year=Integer.parseInt(now_date.split("-")[0]);
                    int month=Integer.parseInt(now_date.split("-")[1]);
                    int day=Integer.parseInt(now_date.split("-")[2]);
                    data.put("fdate",now);
                    data.put("device_id",Integer.parseInt(device_id));
                    List<Map<String,Object>> columns_dlog=dbService.columns("dlog");
                    dbService.save(columns_dlog,"dlog"+device_id,data);
                    sql="INSERT INTO hnww_dloglast SELECT * FROM hnww_dlog" + device_id + " WHERE id="+dlog_id;
                    jdbcTemplate.update(sql);
                    //如果开启软件双发就添加dsendtask
                    if(dsend.equals("1")&&!common.is_empty(field_60))
                    {
                        Map<String,Object> row_dsendtask=new HashMap<>();
                        row_dsendtask.put("device_id",device_id);
                        row_dsendtask.put("dlog_id",dlog_id);
                        row_dsendtask.put("msg","");
                        row_dsendtask.put("ip","");
                        row_dsendtask.put("port",0);
                        row_dsendtask.put("ftime",0);
                        row_dsendtask.put("deleted",0);
                        List<Map<String,Object>> columns_dsendtask=dbService.columns("dsendtask");
                        dbService.save(columns_dsendtask,"dsendtask",row_dsendtask);
                    }
                    //是否有卡号，如果有则更新
                    String iccd=redisUtil.get(channel_id+":iccd");
                    if(!common.is_empty(iccd))
                    {
                        sql="update hnww_device set iccd=?,field_30=? where id=?";
                        jdbcTemplate.update(sql,new Object[]{iccd,iccd,device_id});
                    }
                    else {
                        if(rs1.size()>0)
                        {
                            //说明在收到上报数据的时候，已经有sn的返回，时rtu设备，但是没有iccd，则发送设置指令
                            rabbitUtil.open_iccd(channel_id);
                            rabbitUtil.restart(channel_id);
                        }
                    }
                    String str_year=msg.substring(44,46);
                    if(!str_year.equals("00"))
                    {
                        String respon=common.get_response_old(msg);
                        Map<String,Object> msg_rabbit=new HashMap<>();
                        msg_rabbit.put("type",4);
                        msg_rabbit.put("channel_id",channel_id);
                        msg_rabbit.put("msg",respon);
                        rabbitTemplate.convertAndSend("hnww.respon",msg_rabbit);
                        add_msg(channel_id,4+"",respon,new Date());
                    }
                }
                else {
                    add_msg(channel_id,type,"前期主动上报数据失败:"+msg,new Date());
                    log.info("前期主动上报数据失败:"+msg);
                }
            }
            else if(msg.startsWith("38393836"))
            {
                //心跳包上报卡号
                String iccd=common.hexToASCII(msg);
                redisUtil.set(channel_id+":iccd",iccd,0);
            }
            else
            {
                String action=redisUtil.get(channel_id);
                fileUtil.add_msg("get_msg",channel_id+":action:"+action);
                if(action==null)
                {

                }
                else if(action.equals("05030024"))
                {
                    if(msg.length()==50)
                    {
                        String sn=msg.substring(6,46);
                        sn=common.hexToASCII(sn);
                        fileUtil.add_msg("get_msg",channel_id+":sn:"+sn);
                        sql="select * from hnww_device where sn=? and deleted=0";
                        Object[] ps2={sn};
                        List<Map<String,Object>> rows_device=jdbcTemplate.queryForList(sql,ps2);
                        if(rows_device==null||rows_device.size()==0)
                        {
                            sql="insert into hnww_device (`name`,channel_id,sn,state,deleted) values (?,?,?,?,?);";
                            Object[] ps3={"",channel_id,sn,1,0};
                            int device_id=jdbcTemplate.update(sql,ps3);
                            String table_name = "hnww_dlog" + device_id;
                            sql = "SELECT table_name FROM information_schema.tables where table_name=?";
                            List<Map<String, Object>> list_info = jdbcTemplate.queryForList(sql, new Object[]{table_name});
                            if (list_info.size() == 0)
                            {
                                sql="CREATE TABLE \"hnww\".\""+table_name+"\" (LIKE \"hnww\".\"hnww_dlog\" INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING DEFAULTS INCLUDING COMMENTS);";
                                jdbcTemplate.update(sql);
                            }
                            sql="update hnww_device set table_name=? where id=?";
                            jdbcTemplate.update(sql,new Object[]{table_name,device_id});
                            //添加对应的数据表
                            fileUtil.add_msg("get_msg",channel_id+":sql:"+sql);
                        }
                        else {
                            sql="update hnww_device set channel_id=?,state=1 where sn=?";
                            Object[] ps4={channel_id,sn};
                            jdbcTemplate.update(sql,ps4);
                            fileUtil.add_msg("get_msg",channel_id+":sql:"+sql+":"+sn);
                        }
                        fileUtil.add_msg("online_"+channel_id,sn);
                        //查询版本号
                        String respon="0503001000104447";//获取sn指令
                        Map<String,Object> res=new HashMap<>();
                        res.put("channel_id",channel_id);
                        res.put("msg",respon);
                        rabbitTemplate.convertAndSend("hnww.respon",res);
                        redisUtil.set(channel_id,"05030010",expire);
                        fileUtil.add_msg(channel_id,"send:"+msg);
                    }
                    else {
                        log.info(channel_id+":长度不符合");
                    }
                }
                else if(action.equals("05031201"))
                {
                    if(msg.length()==18)
                    {
                        int interval=Integer.parseInt(msg.substring(6,14),16);
                        if(interval!=60)
                        {
                            rabbitUtil.respon(channel_id,"051012010002040000003CF3E2");
                            rabbitUtil.restart(channel_id);
                        }
                    }
                    else {
                        log.info(channel_id+":长度不符合");
                    }
                }
                else if(action.equals("05030010"))
                {
                    //查询version
                    if(msg.length()==74)
                    {
                        String str="";
                        for(int i=0;i<64;i++)
                        {
                            String s=msg.substring(6+i*2,6+i*2+2);
                            if(!s.equals("00"))
                            {
                                str+=s;
                            }
                            else {
                                i=64;
                            }
                        }
                        if(!str.equals(""))
                        {
                            fileUtil.add_msg("get_msg",channel_id+":version字符串:"+str);
                            String version=common.hexToASCII(str);
                            sql="update "+dbService.prefix+"_device set version=? where channel_id=?";
                            jdbcTemplate.update(sql,new Object[]{version,channel_id});
                        }
                        else {
                            fileUtil.add_msg("get_msg",channel_id+":version字符串为空:"+str);
                        }
                        //更新时间
                        String msg2= common.get_time_msg(new Date());
                        Map<String,Object> res=new HashMap<>();
                        res.put("channel_id",channel_id);
                        res.put("msg",msg2);
                        rabbitTemplate.convertAndSend("hnww.respon",res);
                    }
                    else {
                        log.info(channel_id+":长度不符合");
                    }
                }
                else {
                    //不符合预期的消息
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            fileUtil.add_msg("get_msg",common.format_exception(ex));
            log.info(ex.toString());
        }
    }
    @RabbitListener(queues="hnww.reg",containerFactory="rabbitListenerContainerFactory")
    public void get_reg(Map<String,Object> map)
    {
        try {
            log.info("hnww.reg:"+map.toString());
            String channel_id=map.get("channel_id").toString();
            String type=map.get("type").toString();
//            String sql="insert into hnww_msg (channel,type,channel_id,msg,fdate) values (?,?,?,?,?)";
//            Object[] ps1={"hnww_reg",type,channel_id,"",common.format_date(new Date())};
//            jdbcTemplate.update(sql,ps1);
            add_msg(channel_id,type,"",new Date());
            //查询sn值
            String msg="05030024000A8442";//获取sn指令
            Map<String,Object> res=new HashMap<>();
            res.put("channel_id",channel_id);
            res.put("msg",msg);
            rabbitTemplate.convertAndSend("hnww.respon",res);
            redisUtil.set(channel_id,"05030024",expire);
            redisUtil.set("check_sn:"+channel_id,"-",expire);
            fileUtil.add_msg(channel_id,"send:"+msg);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            log.info(ex.toString());
        }
    }
    @RabbitListener(queues="hnww.timeout",containerFactory="rabbitListenerContainerFactory")
    public void get_timeout(Map<String,Object> map)
    {
        try {
            log.info("hnww.timeout:"+map.toString());
            String channel_id=map.get("channel_id").toString();
            String sql="select * from hnww_device where channel_id='"+channel_id+"'";
            List<Map<String,Object>> rows_device=jdbcTemplate.queryForList(sql);
            boolean kickout=false;
            if(rows_device==null||rows_device.size()==0)
            {
                kickout=true;
            }
            else
            {
                Map<String,Object> row_device=rows_device.get(0);
                String sn=row_device.get("sn").toString();
                if(!sn.startsWith("46010"))
                {
                    kickout=true;
                }
            }
            if(kickout)
            {
                //如果不是前期设备直接踢掉
                Map<String,Object> msg=new HashMap<>();
                msg.put("type",1);
                msg.put("channel_id",channel_id);
                rabbitTemplate.convertAndSend("hnww.kickout",msg);
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            log.info(ex.toString());
        }
    }
    @RabbitListener(queues="hnww.logout",containerFactory="rabbitListenerContainerFactory")
    public void get_logout(Map<String,Object> map)
    {
        try {
            log.info("hnww.logout:" + map.toString());
            String channel_id = map.get("channel_id").toString();
            String sql = "update hnww_device set state=0 where channel_id=?";
            jdbcTemplate.update(sql, channel_id);
            String type = map.get("type").toString();
            add_msg(channel_id,type,"",new Date());
            fileUtil.add_msg("offline",channel_id);
        }
        catch (Exception ex)
        {
            fileUtil.add_msg("get_logout",common.format_exception(ex));
            ex.printStackTrace();
            log.info(ex.toString());
        }
    }

    public void add_check_msg(String id,int type)
    {
        Map<String,Object> msg=new HashMap<>();
        msg.put("type",type);
        msg.put("device_id",id);
        rabbitTemplate.convertAndSend("hnww.check",msg);
//        String sql="insert into hnww_msg (channel,type,channel_id,msg,fdate) values (?,?,?,?,?)";
//        Object[] ps1={"hnww_check",type,id,"",common.format_date(new Date())};
//        jdbcTemplate.update(sql,ps1);
    }
    //当设备掉线和上线和数据过来的时候发送信息到这个队列，然后这里根据队列去尽心告警处理
    //type:0:msg 1：上线 -1：掉线 device_id:设备ID
//    @RabbitListener(queues="hnww.check",containerFactory="rabbitListenerContainerFactory")
    public void get_check(Map<String,Object> map)
    {
        try {
            String type=map.get("type").toString();
            int device_id=Integer.parseInt(map.get("device_id").toString());
            int ftype=1;
            if(!type.equals("0"))
            {
                ftype=0;
            }
            //查询device
            String sql="select * from hnww_device where id=?";
            List<Map<String,Object>> rows_device=jdbcTemplate.queryForList(sql,device_id);
            //查询dlog
            sql="select * from hnww_dlog where device_id=? order by fdate desc limit 0,1";
            Object[] ps={device_id};
            List<Map<String,Object>> rows_dlog=jdbcTemplate.queryForList(sql,ps);

            Object[] ps1={ftype};
            sql="select * from hnww_alarmconfig where deleted=0 and for_site=1 and type=?";
            List<Map<String,Object>> rows_alarmconfig0=jdbcTemplate.queryForList(sql,ps1);
            sql="select * from hnww_alarmconfig where deleted=0 and for_resource=1 and type=?";
            List<Map<String,Object>> rows_alarmconfig1=jdbcTemplate.queryForList(sql,ps1);
            if(rows_device!=null&& rows_device.size()>0)
            {
                Map<String,Object> row_device=rows_device.get(0);
                List<Map<String,Object>> list_alarmconfig=new ArrayList<>();
                int dtype=Integer.parseInt(row_device.get("dtype").toString());
                int detail_id=Integer.parseInt(row_device.get("detail_id").toString());
                if(detail_id>0)
                {
                    if(dtype==0)
                    {
                        //用水单位
                        list_alarmconfig.addAll(rows_alarmconfig0);
                    }
                    else if(dtype==1)
                    {
                        list_alarmconfig.addAll(rows_alarmconfig1);
                    }
                }
                //查询所有alarmconfiglist里面device_id相关的alarmconfig
                sql="select * from hnww_alarmconfig where id in (select alarmconfig_id from hnww_alarmconfiglist where deleted=0 and device_id=?) and deleted=0 and type=?";
                Object[] ps2={device_id,ftype};
                List<Map<String,Object>> rows_alarmconfig=jdbcTemplate.queryForList(sql,ps2);
                list_alarmconfig.addAll(rows_alarmconfig);
                //查询所有已存在rows_alarm
                if(list_alarmconfig.size()>0)
                {
                    sql="select * from hnww_alarm where device_id="+device_id+" and alarmconfig_id in ";
                    String ids="";
                    for(int i=0;i< list_alarmconfig.size();i++)
                    {
                        if(!ids.equals(""))
                        {
                            ids+=",";
                        }
                        ids+=(list_alarmconfig.get(i).get("id").toString());
                    }
                    sql+=("("+ids+") and etime=0 and deleted=0");
                    List<Map<String,Object>> rows_alarm=jdbcTemplate.queryForList(sql);
                    if(ftype==0)
                    {
                        //掉线告警
                        if(type.equals("1"))
                        {
                            //上线，把所有已存在的rows_alarm结束
                            for(int i=0;i<rows_alarm.size();i++)
                            {
                                sql="update hnww_alarm set etime=?,state=1 where id=?";
                                long etime=new Date().getTime();
                                Object[] ps4={etime,rows_alarm.get(i).get("id")};
                                jdbcTemplate.update(sql,ps4);
                            }
                        }
                        else
                        {
                            //下线，循环list_alarmconfig，对于不存在alarm的新增alarm
                            for(int i=0;i< list_alarmconfig.size();i++)
                            {
                                int alarmconfig_id=Integer.parseInt(list_alarmconfig.get(i).get("id").toString());
                                int index=-1;
                                for(int j=0;j< rows_alarm.size();j++)
                                {
                                    if(Integer.parseInt(rows_alarm.get(j).get("alarmconfig_id").toString())==alarmconfig_id)
                                    {
                                        index=j;
                                        j=rows_alarm.size();
                                    }
                                }
                                if(index==-1)
                                {
                                    Map<String,Object> row=new HashMap<>();
                                    row.put("alarmconfig_id",alarmconfig_id);
                                    row.put("device_id",device_id);
                                    row.put("type",ftype);
                                    row.put("field","");
                                    row.put("ftime",(new Date().getTime()));
                                    row.put("etime",0);
                                    row.put("fval",0);
                                    row.put("state",0);
                                    row.put("deleted",0);
                                    List<Map<String,Object>> rows_column=dbService.columns("alarm");
                                    dbService.save(rows_column,"alarm",row);
                                }
                            }
                        }
                    }
                    else
                    {
                        List<Map<String,Object>> rows_column=dbService.columns("alarm");
                        //判断当前最新dlog的参数，如果不存在alarm则新增，如果存在则更新
                        if(rows_dlog!=null&&rows_dlog.size()>0)
                        {
                            Map<String,Object> row_dlog=rows_dlog.get(0);
                            for(int i=0;i<list_alarmconfig.size();i++)
                            {
                                Map<String,Object> row_alarmconfig=list_alarmconfig.get(i);
                                int alarmconfig_id=Integer.parseInt(list_alarmconfig.get(i).get("id").toString());
                                BigDecimal sval=new BigDecimal(row_alarmconfig.get("sval").toString());
                                BigDecimal eval=new BigDecimal(row_alarmconfig.get("eval").toString());
                                String field=row_alarmconfig.get("field").toString();
                                BigDecimal fval=new BigDecimal(row_dlog.get(field)==null?"0":row_dlog.get(field).toString());
                                if(field.equals("flowrate")||field.equals("speed"))
                                {
                                    fval=fval.divide(new BigDecimal(1000));
                                }
                                if(fval.subtract(sval).doubleValue()>=0&&fval.subtract(eval).doubleValue()<=0)
                                {
                                    //告警存在
                                    int index=-1;
                                    for(int j=0;j< rows_alarm.size();j++)
                                    {
                                        if(Integer.parseInt(rows_alarm.get(j).get("alarmconfig_id").toString())==alarmconfig_id)
                                        {
                                            Map<String,Object> row=new HashMap<>();
                                            row.put("id",rows_alarm.get(j).get("id").toString());
                                            row.put("fval",fval);
                                            dbService.save(rows_column,"alarm",row);
                                            index=j;
                                        }
                                    }
                                    if(index==-1)
                                    {
                                        Map<String,Object> row=new HashMap<>();
                                        row.put("alarmconfig_id",alarmconfig_id);
                                        row.put("device_id",device_id);
                                        row.put("type",ftype);
                                        row.put("field",field);
                                        row.put("ftime",(new Date().getTime()));
                                        row.put("etime",0);
                                        row.put("fval",0);
                                        row.put("state",0);
                                        row.put("deleted",0);
                                        dbService.save(rows_column,"alarm",row);
                                    }
                                }
                                else {
                                    //告警消失
                                    for(int j=0;j<rows_alarm.size();j++)
                                    {
                                        if(Integer.parseInt(rows_alarm.get(j).get("alarmconfig_id").toString())==alarmconfig_id)
                                        {
                                            sql = "update hnww_alarm set etime=?,eval=?,state=1 where id=?";
                                            long etime =  new Date().getTime();
                                            Object[] ps4 = {etime,fval, device_id};
                                            jdbcTemplate.update(sql, ps4);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            log.info(ex.toString());
        }
    }

    private void add_msg(String channel_id,String type,String msg,Date date)
    {
        fileUtil.add_msg(channel_id,type+":"+msg);
        fileUtil.add_msg(channel_id,common.format_date(date));
    }
}
